package com.android.jay.lib_audio.mediaplayer.core;

import android.content.Context;
import android.media.AudioManager;

/**
 * Created by wzp on 2020/1/12 0012.
 * <p>
 * 描述  ：音频焦点监听器
 */
public class AudioFocusManager implements AudioManager.OnAudioFocusChangeListener {

    private static final String TAG = AudioFocusManager.class.getSimpleName();
    private AudioFocusListener mListener;
    private AudioManager audioManager;

    public AudioFocusManager(Context context, AudioFocusListener mListener) {
        this.mListener = mListener;
        this.audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    }

    public boolean requestAudioFocus() {
        return audioManager.requestAudioFocus(this,
                AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
    }

    public void abandonAudioFocus(){
        audioManager.abandonAudioFocus(this);
    }

    @Override
    public void onAudioFocusChange(int focusChange) {
        if (mListener != null) {
            switch (focusChange) {
                //重新获得焦点
                case AudioManager.AUDIOFOCUS_GAIN:
                    mListener.audioFocusGrant();
                    break;
                //永久失去焦点 如果被其他播放器抢占了
                case AudioManager.AUDIOFOCUS_LOSS:
                    mListener.audioFocusLoss();
                    break;
                //短暂失去焦点 来电
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                    mListener.audioFocusLossTransient();
                    break;
                //瞬间失去焦点 如通知
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    mListener.audioFocusLossDuck();
                    break;
            }

        }
    }

    public interface AudioFocusListener {
        //获得焦点
        void audioFocusGrant();

        //永久失去焦点回调处理
        void audioFocusLoss();

        //短暂失去焦点回调处理
        void audioFocusLossTransient();

        //瞬间失去焦点
        void audioFocusLossDuck();


    }
}
